package com.kiln.juxingqs.ui

import android.content.Intent
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import client.global.commlib.toast.toast
import client.global.commlib.utils.StringUtil
import client.global.commlib.widget.EmptyLayout
import com.kiln.juxingqs.BaseMiddleActivity
import com.kiln.juxingqs.R
import com.kiln.juxingqs.api.bean.GoodsDetail
import com.kiln.juxingqs.databinding.ActivitySydetailBinding
import com.kiln.juxingqs.databinding.LayoutSydetailBuyitemBinding
import com.kiln.juxingqs.dialog.*
import com.kiln.juxingqs.ui.vm.SyDetailModel
import java.util.*

class SyDetailActivity : BaseMiddleActivity<SyDetailModel, ActivitySydetailBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_sydetail
    }

    override fun initViewModel(): SyDetailModel = createViewModel()

    var jyPrice: String? = null
    var goodsId: String? = null

    override fun initView() {
        binding.vm = viewModel
        binding.event = this

        goodsId = intent.getStringExtra("goodsId")!!
        viewModel.goodId.value = goodsId
        binding.refreshLayout.setOnRefreshListener {
            onRefresh()
        }
        binding.emptyLayout.setOnClickListener {
            onRefresh()
        }
        viewModel.zhRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    toast("转换成功")
                }
            }
        })
    }

    override fun observerUI() {
        viewModel.callUser.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    binding.userInfo = it.data
                }

            }
        })
        viewModel.goodsDetail.observe(this, {
            it?.let {
                if (it.isSuccess && it.data != null) {
                    binding.emptyLayout.visibility = View.GONE
                    binding.bean = it.data

                    var price_d = it.data!!.price.let {
                        it.toDouble() / 2
                    }
                    jyPrice = StringUtil.double2String(price_d, 2)

                    if (it.data!!.collect == 1) {
                        binding.selectTv.isSelected = true
                    } else
                        binding.selectTv.isSelected = false

                    val calendar = Calendar.getInstance()
                    val m = calendar.get(Calendar.MONTH) + 1
                    val d = calendar.get(Calendar.DAY_OF_MONTH)
                    binding.currentDate =
                        "${calendar.get(Calendar.YEAR)}-${if (m < 10) "0${m}" else m}-${d}"
                    val count = Math.max(it.data!!.buy_list.size, it.data!!.sell_list.size)
                    if (count > 0) {
                        binding.buyWrap.removeAllViews()
                        for (i in 0..count - 1) {
                            val buyItemBinding =
                                DataBindingUtil.inflate<LayoutSydetailBuyitemBinding>(
                                    LayoutInflater.from(this@SyDetailActivity),
                                    R.layout.layout_sydetail_buyitem,
                                    binding.buyWrap,
                                    false
                                )

                            if (it.data!!.buy_list.size - 1 >= i) {
                                buyItemBinding.buyNum = "${it.data!!.buy_list[i].surplus_num}"
                                buyItemBinding.buyPrice = "${it.data!!.buy_list[i].price}"
                                buyItemBinding.indexBuy = "${i + 1}"
                            }
                            if (it.data!!.sell_list.size - 1 >= i) {
                                buyItemBinding.sellNum = "${it.data!!.sell_list[i].surplus_num}"
                                buyItemBinding.sellPrice = "${it.data!!.sell_list[i].price}"
                                buyItemBinding.indexSell = "${i + 1}"
                            }

                            binding.buyWrap.addView(buyItemBinding.root)
                        }
                    } else {
                        binding.buyWrap.removeAllViews()
                    }

                } else {
                    if (binding.emptyLayout.visibility != View.GONE)
                        binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
                binding.refreshLayout.isRefreshing = false
                handler.removeCallbacks(runnable)
                handler.removeCallbacksAndMessages(null)
                handler.postDelayed(runnable, 5000) //每5秒执行一次runnable.

            }
        })
        viewModel.guanzRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    binding.bean?.let {
                        if (it.collect == 1) {
                            toast("取消关注")
                            val bean = binding.bean

                            binding.selectTv.isSelected = false

                            bean!!.collect = 0
                            binding.bean = bean
                        } else {
                            toast("已关注")
                            binding.selectTv.isSelected = true

                            val bean = binding.bean
                            bean!!.collect = 1
                            binding.bean = bean
                        }

                    }
                }
            }
        })

        viewModel.guanBuyRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    toast("买入成功")
                    onRefresh()
                }
            }
        })

        viewModel.guanSellRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    toast("卖出成功")
                    onRefresh()

                }
            }
        })
    }

    val handler = Handler()

    val runnable: Runnable = object : Runnable {
        override fun run() {
            //要做的事情
//            binding.buyWrap.removeAllViews()
            viewModel.holdCall(
                intent.getStringExtra("goodsId")!!,
            )
        }
    }


    fun onRefresh() {
        viewModel.userInfo()
        viewModel.holdCall(
            intent.getStringExtra("goodsId")!!,
        )
    }

    fun guaiMai() {
        if (viewModel.priceBuy.value.isNullOrEmpty()) {
            toast("请输入买入价格")
            return
        }
        if (viewModel.buyNum.value.isNullOrEmpty()) {
            toast("请输入买入数")
            return
        }

        if (viewModel.priceBuy.value!!.toDouble() < viewModel.goodsDetail.value!!.data!!.buy_start
            || viewModel.priceBuy.value!!.toDouble() > viewModel.goodsDetail.value!!.data!!.buy_end
        ) {
            toast("价格不能超出范围")
            return
        }
        MsgTitleDialog(this).apply {
            okTxt = "确定"
            cancleTxt = "取消"
            title = "确定买入？"
            ok = {
                viewModel.guaMai()
            }
        }.show()

    }

    //挂卖
    fun holdBath() {
        if (viewModel.goodId.value.isNullOrEmpty()) {
            toast("商品id为空")
            return
        }
        if (viewModel.priceSell.value.isNullOrEmpty()) {
            toast("请输入卖出价格")
            return
        }
        if (viewModel.sellNum.value.isNullOrEmpty()) {
            toast("请输入卖出数")
            return
        }
        if (viewModel.priceSell.value!!.toDouble() < viewModel.goodsDetail.value!!.data!!.sell_start
            || viewModel.priceSell.value!!.toDouble() > viewModel.goodsDetail.value!!.data!!.sell_end
        ) {
            toast("价格不能超出范围")
            return
        }
        MsgTitleDialog(this).apply {
            okTxt = "确定"
            cancleTxt = "不"
            title = "确定卖出？"
            ok = {
                viewModel.guaiSell()
            }
        }.show()
    }

    /**
     * 我的竞拍
     */
    fun myJingpai() {
        startActivity(Intent(this, WdjpActivity::class.java).apply {
            putExtra("goods_id", "${binding.bean!!.goods_id}")
        })
    }

    //转换
    fun zhuanhuan() {
        PagingZhBathDialog(this@SyDetailActivity).apply {
            vm = viewModel
            ok = {
                JyInputNumDialog(this@SyDetailActivity).apply {
                    ok = { num ->
                        viewModel.zhuanhuanPost("${it.bath_id}", "${num}")
                        dismiss()
                    }
                }.show()
            }
        }.show()
    }

    fun goDetail() {
        startActivity(Intent(this, PpDetailActivity::class.java).apply {
            putExtra(
                "banner_list",
                binding.bean!!.banner_list as java.util.ArrayList<GoodsDetail.Banner>
            )
            putExtra(
                "detail_list",
                binding.bean!!.detail_list as java.util.ArrayList<GoodsDetail.Detail>
            )
        })
    }

    fun jyDetail() {
        startActivity(Intent(this, JyDetailActivity::class.java).apply {
            putExtra("goods_id", goodsId)
        })
    }

    fun goZr() {
        startActivity(Intent(this, ZrXyActivity::class.java).apply {
            putExtra("type", 1)
            putExtra("jy_price", jyPrice)
            putExtra("goods_id", goodsId)
        })
    }

    fun goxyZr() {
        startActivity(Intent(this, XyzrActivity::class.java).apply {
        })
    }

    override fun onResume() {
        super.onResume()
//        handler.postDelayed(runnable, 0) //每几秒执行一次runnable. -第二步
        onRefresh()
    }

    override fun onPause() {
        super.onPause()
        handler.removeCallbacks(runnable)
        handler.removeCallbacksAndMessages(null)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(runnable);
        handler.removeCallbacksAndMessages(null)
    }

}